const chalk = require('chalk')
const path = require('path')
// const createApp = require('./app')
const { createBundleRenderer } = require('vue-server-renderer')
const template = require('fs').readFileSync('./src/template/index.template.html', 'utf-8')
const serverBundle = require('../dist/vue-ssr-server-bundle.json')
const clientManifest = require('../dist/vue-ssr-client-manifest.json')
const config = require('../config')



// const renderer = createRenderer({
//   template: require('fs').readFileSync('./src/template/index.template.html', 'utf-8')
// });

const renderer = createBundleRenderer(serverBundle, {
  template,
  clientManifest,
  runInNewContext: false
})

const resolve = file => path.resolve(__dirname, file)
const serve = (path, cache) => express.static(resolve(path), {
  maxAge: cache && isProd ? 1000 * 60 * 60 * 24 *30 : 0
})

const express = require('express')
const server = express()
// server.use('/dist', express.static(resolve('../dist')))
// server.use('/manifest.json', serve('../dist/manifest.json'))

server.use(express.static(resolve('../dist')))

server.get('*', (req, res) => {
  const context = {
    title: 'second ssr app' ,
    url: req.url,
    meta: `
      <meta charset="utf-8" />
    `
  }
  // const app = createApp(context)

  renderer.renderToString(context).then(html => {
    res.end(html)
  }).catch(err => {
    console.log(chalk.red(err))
    res.status(500)
    res.end('Internal Server Error')
  })
})

server.listen(8000, () => {
  console.log(chalk.yellow('server start at 8000'))
})


